<script src="/static/home/js/jquery.min.js"></script>
<script>
var citys = @php echo json_encode($citys);@endphp ;
var provinceCode = '{{$renter->province_code??$provincecode}}';
var cityCode = '{{$renter->city_code??$citycode}}';
var city = '{{$renter->city??""}}';
var region = '{{$renter->region_code??""}}';

layui.use(['upload', 'layer', 'form', 'laydate', 'element'], function () {
    var $ = layui.jquery
        , upload = layui.upload
        , form = layui.form
        , layer = layui.layer
        , laydate = layui.laydate
        , element = layui.element;

    //初始化城市选择
    var html1 = '<option value="">请选择省</option>';
    for (var i in citys) {
        var selected1 = provinceCode == i ? 'selected' : '';
        html1 += '<option value="' + i + '" ' + selected1 + '>' + citys[i].province.name + '</option>';
    }
    if (!!provinceCode) {
        var cityData = citys[provinceCode].city;
        var html2 = '<option value="">请选择市</option>';
        for (var i1 in cityData) {
            var selected2 = cityCode == i1 ? 'selected' : '';
            html2 += '<option value="' + cityData[i1].code + '" ' + selected2 + '>' + cityData[i1].name + '</option>';
        }
    }

    if (!!provinceCode && !!cityCode) {
        var regionData = citys[provinceCode].city[cityCode].region;
        var html3 = '<option value="">请选择县/区</option>';
        for (var i2 in regionData) {
            var selected3 = regionData[i2].code == region ? 'selected' : '';
            html3 += '<option value="' + regionData[i2].code + '" ' + selected3 + '>' + regionData[i2].name + '</option>';
        }
    }

    $('select[name="province_code"]').html(html1);
    $('select[name="city_code"]').html(html2);
    $('input[name="city_code"]').val(city);
    $('select[name="region_code"]').html(html3);
    form.render('select');

    //选择省份
    form.on('select(province)', function (data) {
        var cityInfo = citys[data.value].city;
        var html4 = '<option value="">请选择市</option>';
        for (var i3 in cityInfo) {
            html4 += '<option value="' + cityInfo[i3].code + '">' + cityInfo[i3].name + '</option>';
        }
        $('select[name="city_code"]').html(html4);
        var html5 = '<option value="">请选择县/区</option>'
        $('select[name="region"]').html(html5);
        $("#province_name").val(data.elem[data.elem.selectedIndex].text);
        form.render('select')
    });

    //选择城市
    form.on('select(city)', function (data) {
        var regionInfo = citys[$('select[name="province_code"]').val()].city[data.value].region;
        $('input[name="city_code"]').val(data.elem[data.elem.selectedIndex].text);
        var html6 = '<option value="">请选择县/区</option>';
        for (var i2 in regionInfo) {
            html6 += '<option value="' + regionInfo[i2].code + '" >' + regionInfo[i2].name + '</option>';
        }
        $('select[name="region_code"]').html(html6);
        $("#city_name").val(data.elem[data.elem.selectedIndex].text);
        form.render('select');
    });

    //选择区域
    form.on('select(region)', function (data) {
        //取商圈数据
        var city_code = $("#city_code").val();
        var region_code = $("#region_code").val();
        $("#region_name").val(data.elem[data.elem.selectedIndex].text);
        form.render('select');
    });

    laydate.render({
        elem: '#starttime' //指定元素
    });
    laydate.render({
        elem: '#endtime' //指定元素
    });



    upload.render({
        elem: "#uploadcontracturlbnt"
        , url: '{{ route("api.upload") }}'
        , multiple: true
        , data: {"_token": "{{ csrf_token() }}"}
        , done: function (res) {
            //如果上传失败
            if (res.code == 0) {
                var contracturl = $("#contracturl").val();
                if (contracturl !== "") {
                    $("#contracturl").val(contracturl + "," + res.url);
                }else{
                    $("#contracturl").val( res.url);
                }
                var len = $(".img_box").length;
                var html = '<div class="img_box">';
                    html += '<img layer-pid="" class="img_item" id="contracturl'+len+'" title="点击预览图片" layer-src="'+res.url+'" src="'+res.url+'" width="100px">';
                    html += '<span class="img_del" title="点击删除图片" data-id="'+len+'" data-type="'+len+'">X</span>';
                    html += '</div>';
                $(".imgboxhtml").append(html);
                layer.msg(res.msg);
            } else {
                layer.msg(res.msg, {icon: 2});
            }
        }
    });


    $('.layui-input-inline').on('click','.img_del',function () {
        let id = $(this).data('id');
        layer.confirm('确定删除吗？', {
            btn: ['确认','取消'] //按钮
        }, function(index){
            layer.close(index);
            var valarra = $("#contracturl").val().split(",");
            var delvalue = $("#contracturl"+id).attr("src");
            var newarra = [];
            var len = valarra.length;
            for (let i = 0;i < len; i++) {
                if (valarra[i] != delvalue) {
                    newarra.push(valarra[i]);
                }
            }
            $("#contracturl").val(newarra.join(","));
            $("#contracturl"+id).parent(".img_box").remove();
        }, function(){
            console.log('取消');
        });
    });

    $('.layui-input-inline').on('click','.img_item',function () {
        let elems = $(this).parent().parent();
        let thisSrc = $(this).attr('src');
        let json = {
            "title": "图片预览",
            "id": 1,
            "start": 0,
            "data": []
        }
        let srcArr = [],index = 0;
        elems.find('img').each(function (idx, elem) {
            let src = $(elem).attr('src');
            if(src == thisSrc){
                index = idx
            }
            let item = {
                "alt": "第"+(idx+1)+"张",
                "pid": idx, //图片id
                "src": src, //原图地址
                "thumb": src //缩略图地址
            }
            srcArr.push(item)
        })
        json.start = index;
        json.data = srcArr;
        layer.photos({
            photos: json
            ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
        });
    })

    form.render('select');



    var verify = {
        province:function (value,item){
            if (value == ""){
                return '请选择所属区域-省份';
            }
        },
        city:function (value,item){
            if (value == ""){
                return '请选择所属区域-城市';
            }
        },
        region:function (value,item){
            if (value == ""){
                return '请选择所属区域-区域';
            }
        },
        name:function(value,item){
            if(value == ""){
                return '场租方名称不能为空';
            };
        },
        linkman:function(value,item){
            if(value == ""){
                return '场租方联系人不能为空';
            };
        },
        telephone:function(value,item){
            if(value == ""){
                return '联系人电话不能为空';
            };
        },
        starttime:function(value,item){
            if(value == ""){
                return '合作开始时间不能为空';
            };
        },
        endtime:function(value,item){
            if(value == ""){
                return '合作结束时间不能为空';
            };
        },
        rente_type:function (value,item){
            var rente_type = $('input[name="rente_type"]:checked').val();
            var rente_price = $("#rente_price").val();
            if (rente_type == 1 && rente_price <=0){
                return '场地费用必须大于0';
            }
        },
        property_type:function (value,item){
            var property_type = $('input[name="property_type"]:checked').val();
            var property_price = $("#rente_price").val();
            if (property_type == 1 && property_price <=0 ){
                return '固定物业费用必须大于0';
            }
        },
        operation_type:function (value,item){
            var operation_type = $('input[name="operation_type"]:checked').val();
            var operation_price_A1 = $("#operation_price_A1").val();
            var operation_price_A2 = $("#operation_price_A2").val();
            var operation_price_B1 = $("#operation_price_B1").val();
            var operation_price_B2 = $("#operation_price_B2").val();
            if (operation_type == 1 && operation_price_A1 <=0 ){
                return '我方分润比例必须大于0';
            }
            if (operation_type == 1 && operation_price_A2 <= 0){
                return '场地方分润比例必须大于0';
            }
            if (operation_type == 2 && operation_price_B1 <= 0){
                return '单笔分润必须大于0';
            }
            if (operation_type == 2 && operation_price_B2 <= 0){
                return '保底月收必须大于等于0';
            }
        },
        contracturl:function(value,item){
            if(value == ""){
                return '请上传合同';
            };
        }
    };
    form.verify(verify);

    form.on('submit(formDemo)', function (data) {
        //console.log(data.field); // 表单数据 {name:value}

        var flag = true;
        console.log(flag);

        if (flag == true){
            form.submit();
        }else{
            return false;
        }


    });

});

function downloadImg(id) {
    location.href = "/admin/estate/downloadhetong?id={{$property->id??0}}&_token={{ csrf_token() }}";
}

//plupload中为我们提供了mOxie对象
//有关mOxie的介绍和说明请看：https://github.com/moxiecode/moxie/wiki/API
//file为plupload事件监听函数参数中的file对象,callback为预览图片准备完成的回调函数
function previewImage(file,callback){
    if(!file || !/image\//.test(file.type)) return; //确保文件是图片
    if(file.type=='image/gif'){ //gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
        var gif = new moxie.file.FileReader();
        gif.onload = function(){
            callback(gif.result);
            gif.destroy();
            gif = null;
        };
        gif.readAsDataURL(file.getSource());
    }else{
        var image = new moxie.image.Image();
        image.onload = function() {
            image.downsize( 150, 150 );//先压缩一下要预览的图片,宽300，高300
            var imgsrc = image.type=='image/jpeg' ? image.getAsDataURL('image/jpeg',80) : image.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
            callback && callback(imgsrc); //callback传入的参数为预览图片的url
            image.destroy();
            image = null;
        };
        image.load( file.getSource() );
    }
}
</script>